package com.orange.off.cloud.cloudoff.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.orange.off.cloud.cloudoff.R;
import com.orange.off.cloud.cloudoff.activity.IntermediaryActivity;
import com.orange.off.cloud.cloudoff.activity.MainActivity;
import com.orange.off.cloud.cloudoff.app.MyApplication;
import com.orange.off.cloud.cloudoff.events.RegisteredEvent;
import com.orange.off.cloud.cloudoff.model.UploadResponse;
import com.orange.off.cloud.cloudoff.urls.AppUrls;
import com.orange.off.cloud.cloudoff.utils.JsonUtils;
import com.orange.off.cloud.cloudoff.utils.ProgressDlgUtil;
import com.orange.off.cloud.cloudoff.utils.SPUtil;
import com.orange.off.cloud.cloudoff.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

/**
 * 登录
 *
 * @author smile
 */
public class LoginFragment extends Fragment {


    @Bind(R.id.login_user_edit)
    EditText loginUserEdit;
    @Bind(R.id.login_user_clear)
    ImageView loginUserClear;
    @Bind(R.id.login_password_edit)
    EditText loginPasswordEdit;
    @Bind(R.id.login_password_clear)
    ImageView loginPasswordClear;
    @Bind(R.id.login_account_button)
    Button loginAccountButton;
    @Bind(R.id.login_account_linear)
    LinearLayout loginAccountLinear;
    @Bind(R.id.login_forget_pwd)
    TextView loginForgetPwd;
    @Bind(R.id.login_submit_button)
    Button loginSubmitButton;
    Boolean isAccount = true;
    @Bind(R.id.login_registered_button)
    Button loginRegisteredButton;

    public static LoginFragment newInstance() {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        initListeners();
        initViews();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.login_fragment, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    private void initListeners() {

        //清空输入的用户名
        loginUserClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUserEdit.setText("");
            }
        });

        //监控输入
        loginUserEdit.addTextChangedListener(mTextWatcher1);

        //清空输入的用户名
        loginPasswordClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginPasswordEdit.setText("");
            }
        });

        //监控输入
        loginPasswordEdit.addTextChangedListener(mTextWatcher2);
    }


    private void initViews() {
        String user = (String) SPUtil.get(getActivity(), "username", "");
        String pwd = (String) SPUtil.get(getActivity(), "password", "");
        //        String num = PhoneUtils.getPhoneNumber(getActivity());
        if (!TextUtils.isEmpty(user)) {
            loginUserEdit.setText(user);
            loginUserClear.setVisibility(View.VISIBLE);
        }
        if (!TextUtils.isEmpty(pwd)) {
            loginPasswordEdit.setText(pwd);
            loginPasswordClear.setVisibility(View.VISIBLE);
        }

        if ((Boolean) SPUtil.get(getActivity(), "isMemory", true)) {
            isAccount = true;
            loginAccountButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_check_true));
        } else {
            isAccount = false;
            loginAccountButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_check_false));
        }
    }

    //监控电话输入
    TextWatcher mTextWatcher1 = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!loginUserEdit.getText().toString().equals("")) {
                loginUserClear.setVisibility(View.VISIBLE);
            } else {
                loginUserClear.setVisibility(View.INVISIBLE);
            }
        }
    };

    //监控密码输入
    TextWatcher mTextWatcher2 = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!loginPasswordEdit.getText().toString().equals("")) {
                loginPasswordClear.setVisibility(View.VISIBLE);
            } else {
                loginPasswordClear.setVisibility(View.INVISIBLE);
            }
        }
    };

    @OnClick({R.id.login_account_button, R.id.login_account_linear, R.id.login_forget_pwd, R.id.login_submit_button
            , R.id.login_registered_button})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_account_button:
                AccountButton();
                break;
            case R.id.login_account_linear:
                AccountButton();
                break;
            case R.id.login_forget_pwd:
                //忘记密码：
                Intent intent2 = new Intent(getActivity(), IntermediaryActivity.class);
                intent2.putExtra("type", IntermediaryActivity.FORGETPWD);
                startActivity(intent2);
                break;
            case R.id.login_submit_button:
                final String userName = loginUserEdit.getText().toString().trim();
                final String password = loginPasswordEdit.getText().toString().trim();
                if (TextUtils.isEmpty(userName)) {
                    ToastUtils.show(getActivity(), "手机号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    ToastUtils.show(getActivity(), "密码不能为空");
                    return;
                }
                ProgressDlgUtil.showProgressDlg("登录中,请稍后...", getActivity());
                loginSubmitButton.setEnabled(false);
                RequestParams params = new RequestParams();
                params.addFormDataPart("account", userName);
                params.addFormDataPart("mima", password);
                Log.d(MyApplication.DEBUG, "login---》" + "account--->" + userName + "----password--->" + password);
                HttpRequest.post(AppUrls.Login, params, new BaseHttpRequestCallback<UploadResponse>() {
                    @Override
                    public void onSuccess(UploadResponse uploadResponse) {
                        super.onSuccess(uploadResponse);
                        ProgressDlgUtil.stopProgressDlg();
                        loginSubmitButton.setEnabled(true);
                        Log.d(MyApplication.DEBUG, "login--success-》" + uploadResponse.toString());

                        if (uploadResponse.getSuccess()) {
                            ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);

                            try {
                                JSONObject jsonObject = new JSONObject(uploadResponse.getData());
                                String aid = JsonUtils.getString(jsonObject, "aid", "");
                                MyApplication.aid = aid;
                                if (isAccount) {
                                    SPUtil.put(getActivity(), "username", userName);
                                    SPUtil.put(getActivity(), "userid", aid);
                                    SPUtil.put(getActivity(), "password", password);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Intent intent = new Intent(getActivity(), MainActivity.class);
                            startActivity(intent);
                            getActivity().finish();
                        } else {
                            ToastUtils.show(getActivity(), uploadResponse.getMessage(), Toast.LENGTH_SHORT);
                        }

                    }

                    @Override
                    public void onFailure(int errorCode, String msg) {
                        super.onFailure(errorCode, msg);
                        ProgressDlgUtil.stopProgressDlg();
                        loginSubmitButton.setEnabled(true);
                        Log.d(MyApplication.DEBUG, "登录失败---》" + "errorCode------" + errorCode + "---" + msg);
                    }

                    @Override
                    public void onProgress(int progress, long networkSpeed, boolean done) {
                    }
                });
                break;
            case R.id.login_registered_button:
                Intent intent = new Intent(getActivity(), IntermediaryActivity.class);
                intent.putExtra("type", IntermediaryActivity.REGISTERED);
                startActivity(intent);
                break;
        }
    }


    private void AccountButton() {
        if (isAccount) {
            SPUtil.remove(getActivity(), "username");
            SPUtil.remove(getActivity(), "password");
            SPUtil.put(getActivity(), "isMemory", false);
            isAccount = false;
            loginAccountButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_check_false));
        } else {
            SPUtil.put(getActivity(), "isMemory", true);
            isAccount = true;
            loginAccountButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_check_true));
        }
    }

    /**
     * EventBus：注册成功事件通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRegisteredEvent(RegisteredEvent event) {
        loginUserEdit.setText(event.phone);
        loginPasswordEdit.setText(event.password);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    private long waitTime = 2000;
    private long touchTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            exit();
            return true;
        }
        return false;
    }

    private void exit() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - touchTime >= waitTime) {
            ToastUtils.show(getActivity(), R.string.exit_show);
            touchTime = currentTime;
        } else {
            getActivity().finish();
        }
    }

}
